package com.dianrui.firemenmonitor.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dianrui.firemenmonitor.Constant;
import com.dianrui.firemenmonitor.MyApplication;
import com.dianrui.firemenmonitor.R;
import com.dianrui.firemenmonitor.event.ChangeName;
import com.dianrui.firemenmonitor.event.RreshMy;
import com.dianrui.firemenmonitor.util.BitmapUtils;
import com.dianrui.firemenmonitor.util.ConvertUtils;
import com.dianrui.firemenmonitor.util.GlideUtil;
import com.dianrui.firemenmonitor.util.MyUtil;
import com.dianrui.firemenmonitor.util.OkHttpUtils;
import com.dianrui.firemenmonitor.util.StringUtils;
import com.dianrui.firemenmonitor.util.ToastUtil;
import com.dianrui.firemenmonitor.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

public class EditPersonInfoActivity extends BaseActivity {
    private ProgressDialog pd;

    @BindView(R.id.pic)
    ImageView pic;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.show_names)
    TextView showNames;
    @BindView(R.id.show_number)
    TextView showNumber;
    @BindView(R.id.show_mobile)
    TextView showMobile;

    @Override
    public int getContentViewId() {
        return R.layout.edit_person_info;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(R.color.blue_518bfa);
        pd = new ProgressDialog(this);
        title.setText(getString(R.string.editperson_title));
        topRight.setVisibility(View.GONE);
        topRight.setText(getString(R.string.save));
        if(!StringUtils.isEmpty(spUtils.getString("userimg"))){
            GlideUtil.loadUserImageViewSize(getApplicationContext(), spUtils.getString("userimg"), pic);
        }
        if(!StringUtils.isEmpty(spUtils.getString("username"))){
            showNames.setText(spUtils.getString("username"));
        }
        if(!StringUtils.isEmpty(spUtils.getString("policesignal"))){
            showNumber.setText(spUtils.getString("policesignal"));
        }
        if (!StringUtils.isEmpty(spUtils.getString("phone")) && spUtils.getString("phone").length() > 6) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < spUtils.getString("phone").length(); i++) {
                char c = spUtils.getString("phone").charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
            showMobile.setText(sb.toString());
        }
        getPersonInfo();

    }

    private void getPersonInfo() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.PERSONCENTER, "", new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("userimg"))) {
                                    GlideUtil.loadUserImageViewSize(getApplicationContext(), jsonObject.optJSONObject("data").optString("userimg"), pic);
                                }
                                showNames.setText(jsonObject.optJSONObject("data").optString("username"));
                                showNumber.setText(jsonObject.optJSONObject("data").optString("policesignal"));
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("phone")) && jsonObject.optJSONObject("data").optString("phone").length() > 6) {
                                    StringBuilder sb = new StringBuilder();
                                    for (int i = 0; i < jsonObject.optJSONObject("data").optString("phone").length(); i++) {
                                        char c = jsonObject.optJSONObject("data").optString("phone").charAt(i);
                                        if (i >= 3 && i <= 6) {
                                            sb.append('*');
                                        } else {
                                            sb.append(c);
                                        }
                                    }
                                    showMobile.setText(sb.toString());
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    @OnClick({R.id.back, R.id.click_pic, R.id.top_right, R.id.click_name, R.id.click_number,R.id.click_mobile})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.top_right:
                break;
            case R.id.click_pic:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(EditPersonInfoActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        choosePicUserImage();
                    } else {
                        ActivityCompat.requestPermissions(EditPersonInfoActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    choosePicUserImage();
                }
                break;
            case R.id.click_name:
                Intent changeNameintent=new Intent(EditPersonInfoActivity.this, ChangNameActivity.class);
                Bundle changeNamebundle=new Bundle();
                changeNamebundle.putString("nickname", showNames.getText().toString());
                changeNameintent.putExtras(changeNamebundle);
                startActivity(changeNameintent);
                break;
            case R.id.click_number:
                break;
            case R.id.click_mobile:
               JumpActivitys(ChangeMobileActivity.class);
                break;
                default:
                    break;
        }
    }

    //选择拍照或者相册选图
    private void choosePicUserImage() {
        MyUtil.createPhotoChooseDialog(0, 1, EditPersonInfoActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
            @Override
            public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                if (resultList == null && resultList.size() == 0) {
                    ToastUtil.showToast("照片未选中");
                    return;
                }
                GlideUtil.loadUserImageViewSize(getApplicationContext(), resultList.get(0).getPhotoPath(), pic);
                setInfoFace(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight())));
            }

            @Override
            public void onHanlderFailure(int requestCode, String errorMsg) {}
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)//修改昵称后更新本地并上传给后台
    public void onMessageEvent(ChangeName changeName) {
        showNames.setText(changeName.name);
        setInfoName(changeName.name);
    }

    private void setInfoName(String value) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("username", value);
        OkHttpUtils.getInstance().postWithMemberToken(Url.SETINFO, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                ToastUtil.showToast(jsonObject.optString("msg"));
                                EventBus.getDefault().post(new RreshMy());
                                spUtils.put("username", jsonObject.optJSONObject("data").optString("username"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    private void setInfoFace(String value) {
        pd.setMessage("正在上传头像中...");
        pd.show();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("file", value);
        OkHttpUtils.getInstance().postWithMemberToken(Url.SETINFO, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                pd.dismiss();
                                ToastUtil.showToast(jsonObject.optString("msg"));
                                spUtils.put("userimg", jsonObject.optJSONObject("data").optString("userimg"));
                                EventBus.getDefault().post(new RreshMy());
                            } else {
                                pd.dismiss();
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        pd.dismiss();
                        e.printStackTrace();
                    }
                } else {
                    pd.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
